<template>
    <Dialog
      :show="dialogConfig.show"
      :title="dialogConfig.title"
      :buttons="dialogConfig.buttons"
      :showCancel="true"
      @close="dialogConfig.show = false"
    >
      <el-form
        :model="formData"
        :rules="rules"
        ref="formDataRef"
        label-width="80px"
        @submit.prevent
      >
        <el-form-item label="用户名" prop="userName">
          <el-input   :maxLength="10" v-model="formData.userName" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
           :maxLength="50" v-model="formData.email" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input   :maxLength="11" v-model="formData.phone" />
        </el-form-item>
    </el-form>
    </Dialog>
  </template>

  <script setup>
  import { ref, reactive, getCurrentInstance, nextTick } from "vue";
  const { proxy } = getCurrentInstance();

  const api = {
    saveAccount: "/saveMyInfo",
  };

  const dialogConfig = ref({
    show: false,
    title: "新增账号",
    buttons: [
      {
        type: "primary",
        text: "确定",
        click: (e) => {
          submitForm();
        },
      },
    ],
  });

  const formData = ref({});
  const formDataRef = ref();

  const rules = {
    userName: [{ required: true, message: "请输入用户名" }],
    phone: [
      { required: true, message: "请输入手机号" },
      {
        validator: proxy.Verify.phone,
        trigger: "blur",
        message: "请输入正确的手机号",
      },
    ],
    email: [
    { required: true, message: "请输入邮箱" },
      {
        validator: proxy.Verify.email,
        trigger: "blur",
        message: "请输入正确的邮箱",
      },
    ],
  };

  const showEdit = (data) => {
    dialogConfig.value.show = true;
    nextTick(() => {
      formDataRef.value.resetFields();
      if (data.userId == null) {
        dialogConfig.value.title = "修改账号信息";

      } else {
        dialogConfig.value.title = "修改账号";
        let editData = Object.assign({}, data);
        formData.value = Object.assign({}, editData);
      }
    });
  };

  defineExpose({
    showEdit,
  });

  const emit = defineEmits(["reload"]);
  const submitForm = async () => {
    formDataRef.value.validate(async (valid) => {
      if (!valid) {
        return;
      }
      let params = {};
      Object.assign(params, formData.value);

      let result = await proxy.Request({
        url: api.saveAccount,
        params,
      });
      if (!result) {
        return;
      }
      dialogConfig.value.show = false;
      proxy.Message.success("保存成功");
      emit("reload");
    });
  };
  </script>

  <style lang="scss" scoped>
  .check-span-item {
    float: left;
    margin-right: 10px;
    line-height: 20px;
  }
  </style>
